package xdu.lz.stage6_threadpool.chapter2_excutors_threadPoolImpl;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created at 2019/10/23 0023 下午 9:54
 * --
 */
public class FixedSizeThreadPool {


    /**
     * coreSize = MaxSize = n;
     * keepAliveTime = 0 ，因为Idel中 maxSize ！> coreSize 所以不会回收
     * blockingQueue = LinkedBlockingQueue,给了默认构造函数个数Integer.MAX_VALUE
     * threadFactory = Executors.defaultThreadFactory implements ThreadFactory interface
     * <p>
     * <p>
     * <p>
     * 不会自动关闭
     *
     * @return
     */
    private static ExecutorService newFixedThreadPool() {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);

        System.out.println("getActiveCount = " + executor.getActiveCount());

        System.out.println("getActiveCount = " + executor.getActiveCount());

        for (int i = 0; i < 50; i++) {
            executor.execute(() -> {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        System.out.println("getActiveCount = " + executor.getActiveCount());
        return executor;
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor service = (ThreadPoolExecutor) newFixedThreadPool();
        int size = -1;
        while (true) {
            if (size != service.getActiveCount()) {
                System.out.println("getActiveCount = " + service.getActiveCount());
                size = service.getActiveCount();
                Thread.sleep(10);
            }
            if (size == 0)
                break;
        }

        System.out.println("所有任务执行完毕，不会被销毁");
    }
}
